import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import {
  ElCard,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElButton,
  ElSpace,
  ElLink,
  ElDatePicker,
  ElMessage,
  ElMessageBox
} from 'element-plus'

import type { FormValuesType } from './typings'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { alarmNameEnum, workAreaEnum, fnStateEnum } from '~/store/monitor/typings'

import ProSaasTable from '~/components/ProSaasTable'
import useVuexGetters from '~/hooks/useVuexGetters'
import AliIcon from '~/components/AliIocn'
import ExportExcel from '~/components/ExportExcel'
import styles from '../../index.module.scss'
import ColorfulBadge from '~/components/ColorfulBadge'
import ColorfulBadgeMore from '~/components/ColorfulBadgeMore'

export default defineComponent(function PoliceEquipment() {
  const store = useStore()
  const router = useRouter()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<FormValuesType>({})
  const policeState = useVuexGetters('police', [
    'alarmNameOpt',
    'workAreaOpt',
    'alarmStatusOpt',
    'alarmStatusEnum',
    'ignoreStatusOpt',
    'ignoreStatusEnum'
  ])
  const state = reactive({
    exportVisible: false
  })
  const userState = useVuexGetters('user', ['permission'])
  const columns: TableColumnProps<FormValuesType>[] = [
    {
      label: '警报名称',
      prop: 'alarmName',
      minWidth: 140,
      fixed: 'left',
      unFixed: true,
      showOverflowTooltip: true,
      sortable: true,
      disabled: true
    },
    {
      label: '设备名称',
      prop: 'deviceName',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '所属工区',
      prop: 'workAreaName',
      minWidth: 120,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '开关回路',
      prop: 'loopName',
      minWidth: 120,
      showOverflowTooltip: true,
      align: 'center',
      sortable: true
    },
    {
      label: '警报值',
      prop: 'alarmValue',
      minWidth: 120,
      showOverflowTooltip: true,
      align: 'center',
      sortable: true
    },
    {
      label: '警报状态',
      prop: 'alarmState',
      minWidth: 160,
      showOverflowTooltip: true,
      enumValues: policeState.alarmStatusEnum,
      align: 'center',
      sortable: true,
      render: (option, value) => (
        <ColorfulBadge
          value={value}
          enumKey={option.row.alarmState as unknown as number}
          options={{ success: 0, warning: 1 }}
        />
      )
    },
    {
      label: '警报时间',
      prop: 'reportTime',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '恢复时间',
      prop: 'recoverTime',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '工单状态',
      prop: 'orderState',
      minWidth: 140,
      showOverflowTooltip: true,
      align: 'center',
      sortable: true,
      render: (option, value) => (
        <ColorfulBadgeMore
          value={value}
          enumKey={option.row.orderState as string}
          options={{
            success: '已归档',
            warning: ['待确认', '待发送', '待处理', '待分配', '待归档', '待终结'],
            danger: '未推送'
          }}
        />
      )
    },
    {
      label: '忽略状态',
      prop: 'ignoreState',
      minWidth: 160,
      hidden: true,
      showOverflowTooltip: true,
      enumValues: policeState.ignoreStatusEnum,
      align: 'center',
      sortable: true,
      render: (option, value) => (
        <ColorfulBadge
          value={value}
          enumKey={option.row.ignoreState as unknown as number}
          options={{ success: 1, info: 0 }}
        />
      )
    },

    {
      label: '设备编号',
      prop: 'deviceUid',
      minWidth: 160,
      hidden: true,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '线路/相位',
      prop: 'loopPhase',
      minWidth: 160,
      hidden: true,
      showOverflowTooltip: true,
      align: 'center',
      sortable: true
    },
    {
      label: '警报地点',
      prop: 'alarmAddress',
      minWidth: 160,
      hidden: true,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '操作',
      prop: 'options',
      minWidth: 230,
      align: 'center',
      fixed: 'right',
      unFixed: true,
      disabled: true,
      render: ({ row }) => (
        <ElSpace>
          {userState.permission.value.has('alarm_alarmInfo_ignore') && !row.ignoreState && (
            <ElLink type="primary" onClick={() => ignore(row)}>
              <AliIcon type="icon-hulve1" />
              &nbsp; 忽略&nbsp;&nbsp;
            </ElLink>
          )}
          <ElLink type="primary" onClick={() => infoOpen(row)}>
            <AliIcon type="icon-chakan" />
            &nbsp; 详情&nbsp;&nbsp;
          </ElLink>
          {userState.permission.value.has('alarm_alarmInfo_push') && row.orderState === '未推送' && (
            <ElLink type="primary" onClick={() => pushOrder(row)}>
              <AliIcon type="icon-yichu1" />
              &nbsp; 推送工单
            </ElLink>
          )}
        </ElSpace>
      )
    }
  ]

  onMounted(() => {
    //  警报名称
    store.dispatch('police/SelectAlarmBoxList')
    //  所属工区
    store.dispatch('police/SelectAreaNameBoxList')
    //  警报状态
    store.dispatch('police/AlarmStatusOpt', { code: 'device_alarm_state' })
    //  忽略状态
    store.dispatch('police/IgnoreStatusOpt', { code: 'device_alarm_ignoreState' })

    const row: FormValuesType = router.currentRoute.value.query
    if (row.deviceName) {
      formValues.keyWord = row.deviceName
    }
    if (row.alarmName) {
      formValues.alarmName = row.alarmName
    }
    if (row.deviceName || row.alarmName) {
      setTimeout(() => {
        proSaasTableRef.value!?.toSearch()
      }, 500)
    }
  })
  //  推送工单
  const pushOrder = (row: FormValuesType) => {
    orderAjax(row.id, true)
  }
  //  批量推送工单
  const allPushOrder = () => {
    const ids = proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    if (!ids) {
      ElMessage({ type: 'warning', message: '请勾选数据' })
      return
    }
    orderAjax(ids, false)
  }
  //  推送工单请求
  const orderAjax = async (ids: any, value: boolean) => {
    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>
          {value && <p class="delete-title">确认推送工单?</p>}
          {!value && (
            <p class="delete-title">
              {proSaasTableRef.value!.selecteds?.length > 1
                ? `确认推送选中的${proSaasTableRef.value!.selecteds?.length}条数据?`
                : '确认推送选中数据？'}
            </p>
          )}
          {/* <p class="delete-content">推送后不可恢复，是否确认推送。</p> */}
        </section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    }).then(async () => {
      const { code } = await store.dispatch('police/PushOrder', { alarmInfoIds: ids })
      if (code === 200) {
        proSaasTableRef.value!?.clearSelection?.()
        proSaasTableRef.value!?.toSearch()
        ElMessage({ type: 'success', message: '操作成功' })
      }
    })
  }
  //  忽略
  const ignore = (row: FormValuesType) => {
    ignoreAjax(row.id, true)
  }
  //  批量忽略
  const allIgnore = () => {
    const ids = proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    if (!ids) {
      ElMessage({ type: 'warning', message: '请勾选数据' })
      return
    }
    ignoreAjax(ids, false)
  }
  //  忽略请求
  const ignoreAjax = async (ids: any, value: boolean) => {
    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>
          {value && <p class="delete-title">确认忽略警报信息?</p>}
          {!value && (
            <p class="delete-title">
              {proSaasTableRef.value!.selecteds?.length > 1
                ? `确认忽略选中的${proSaasTableRef.value!.selecteds?.length}条数据?`
                : '确认忽略选中数据？'}
            </p>
          )}
          {/* <p class="delete-content">忽略后不可恢复，是否确认推送。</p> */}
        </section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    }).then(async () => {
      const { code } = await store.dispatch('police/IgnoreAlarm', { alarmInfoIds: ids })
      if (code === 200) {
        proSaasTableRef.value!?.clearSelection?.()
        proSaasTableRef.value!?.toSearch()
        ElMessage({ type: 'success', message: '操作成功' })
      }
    })
  }
  //  跳转到详情
  const infoOpen = (row: FormValuesType) => {
    router.push({ path: '/monitor/police/data/info', query: { id: row.id } })
  }
  //  合并推送
  const orderOpen = () => {
    const ids = proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    if (!ids) {
      ElMessage({ type: 'warning', message: '请勾选数据' })
      return
    }
    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>
          {
            <p class="delete-title">
              {proSaasTableRef.value!.selecteds?.length > 1
                ? `确认合并推送选中的${proSaasTableRef.value!.selecteds?.length}条数据?`
                : '确认合并推送选中数据？'}
            </p>
          }
          {/* <p class="delete-content">合并推送后不可恢复，是否确认合并推送。</p> */}
        </section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    }).then(async () => {
      const { code } = await store.dispatch('police/PushAnyOrder', { alarmInfoIds: ids })
      if (code === 200) {
        proSaasTableRef.value!?.clearSelection?.()
        proSaasTableRef.value!?.toSearch()
        ElMessage({ type: 'success', message: '操作成功' })
      }
    })
  }
  //  按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }
  //  清空搜索
  const clearSearchTable = async () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }
  // 打开导出弹框
  const handleChangeExportModal = () => {
    state.exportVisible = !state.exportVisible
  }

  return () => {
    // 日期变时 搜索
    const props = {
      onChange: () => {
        setTimeout(() => {
          proSaasTableRef.value!?.toSearch()
        }, 100)
      }
    }

    return (
      <ElCard>
        <ProSaasTable<FormValuesType>
          tableId="monitor_police_data_index"
          ref={proSaasTableRef}
          columns={columns}
          searchParams={{
            beginTime: formValues.times?.[0],
            endTime: formValues.times?.[1]
          }}
          hasSelection
          dispatchType="police/AlarmInfoList"
          searchFormProps={{
            model: formValues
          }}
          headerTitle={
            <>
              {userState.permission.value.has('alarm_alarmInfo_push') && (
                <ElButton type="primary" onClick={allPushOrder}>
                  <AliIcon type="icon-yichu1" />
                  &nbsp; 推送工单
                </ElButton>
              )}
              {userState.permission.value.has('alarm_alarmInfo_anypush') && (
                <ElButton type="primary" onClick={orderOpen}>
                  <AliIcon type="icon-yichu1" />
                  &nbsp; 合并推送
                </ElButton>
              )}
              {userState.permission.value.has('alarm_alarmInfo_ignore') && (
                <ElButton type="danger" onClick={allIgnore}>
                  <AliIcon type="icon-hulve1" />
                  &nbsp; 批量忽略
                </ElButton>
              )}
              {userState.permission.value.has('alarm_alarmInfo_export') && (
                <ElButton type="success" onClick={handleChangeExportModal}>
                  <AliIcon type="icon-daochu" />
                  &nbsp; 导出
                </ElButton>
              )}
            </>
          }
          searchformResponsiveCol={[
            <ElFormItem key="keyWord" prop="keyWord" label="">
              <ElInput
                v-model={formValues.keyWord}
                placeholder="设备名称或设备编号"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>,
            <ElFormItem key="alarmName" prop="alarmName">
              <ElSelect
                v-model={formValues.alarmName}
                clearable
                placeholder="请选择警报名称"
                onChange={clearSearchTable}
                filterable
              >
                {policeState.alarmNameOpt?.value?.map((item: alarmNameEnum) => (
                  <ElOption key={item?.id} label={item?.alarmName} value={item?.alarmName} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="workAreaId" prop="workAreaId">
              <ElSelect
                v-model={formValues.workAreaId}
                clearable
                placeholder="请选择所属区域"
                onChange={clearSearchTable}
                filterable
              >
                {policeState.workAreaOpt?.value?.map((item: workAreaEnum) => (
                  <ElOption key={item?.id} label={item?.name} value={item?.id} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="alarmState" prop="alarmState">
              <ElSelect
                v-model={formValues.alarmState}
                clearable
                placeholder="请选择警报状态"
                onChange={clearSearchTable}
              >
                {policeState.alarmStatusOpt?.value?.map((item: fnStateEnum) => (
                  <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="ignoreState" prop="ignoreState">
              <ElSelect
                v-model={formValues.ignoreState}
                clearable
                placeholder="请选择忽略状态"
                onChange={clearSearchTable}
              >
                {policeState.ignoreStatusOpt?.value?.map((item: fnStateEnum) => (
                  <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="times" prop="times">
              <ElDatePicker
                v-model={formValues.times}
                start-placeholder="警报开始时间"
                end-placeholder="警报结束时间"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                type="datetimerange"
                {...props}
              />
            </ElFormItem>
          ]}
        />
        {state.exportVisible && (
          <ExportExcel
            visible={state.exportVisible}
            dispatchType="police/AlarmInfoExport"
            columns={proSaasTableRef.value?.filterColumns}
            payload={{ params: formValues }}
            onCancel={handleChangeExportModal}
          />
        )}
      </ElCard>
    )
  }
})
